
import 'dart:async';
import 'package:date_format/date_format.dart';

import 'package:bookshelf/http/api.dart';
import 'package:bookshelf/util/timer_manager.dart';
import 'package:bookshelf/util/toast_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../entity/return_entity.dart';
import '../event/inventory_rfid_event.dart';
import '../main.dart';
import '../serial/three_to_one_manager.dart';
import '../widget/app_bar.dart';


class Return extends StatefulWidget {
  const Return({Key? key}) : super(key: key);

  @override
  State<Return> createState() => _ReturnState();
}

class _ReturnState extends State<Return> {

  final RxList<ReturnEntity> _list = RxList();
  ThreeToOneManager manager = ThreeToOneManager();
  StreamSubscription? borrowSubscription;

  @override
  initState() {
    super.initState();
    tts.speak('请将图书标签贴至扫描区');


    borrowSubscription = eventFactory.on<InventoryRfidEvent>().listen((event) {
      if(_list.map((element) => element.bookNo).contains(event.no)) {
        _setModeAndStart();
        return;
      }
      _return(event.no);
    });


    WidgetsBinding.instance.addPostFrameCallback((_){
      timer.startCountDown(CountDownMode.action, (){
        currentTask.clear();
        timer.cancel();
        manager.setMode(Mode.none);
        Get.until((route) => route.isFirst);
      });
    });
    _setModeAndStart();
  }

  _setModeAndStart(){
    try{
      manager.setModeAndStart(Mode.inventory,isBorrow: false);
    }catch(e){
      toastWarn('三合一读写器配置错误');
      print(e);
    }
  }

  @override
  void dispose() {
    borrowSubscription?.cancel();
    borrowSubscription = null;
    super.dispose();
  }

  _return(book) async {
    if(book == null){
      toastWarn('条码号异常');
    }else{
      var data = await bookReturn(book);
      if(data != null){
        tts.speak('归还成功');
        _list.insert(0, data);
      }
    }
    _setModeAndStart();
  }


  _title(){
    return Container(
      margin: EdgeInsets.only(top: 10.h,left: 8.w,right: 8.w,bottom: 10.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          InkWell(
            onTap: (){
              currentTask.clear();
              timer.cancel();
              manager.setMode(Mode.none);
              Get.back();
            },
            child: Image.asset("assets/images/back.png",width:50.w,fit: BoxFit.fitWidth,),
          ),
          Text("归还列表",style: TextStyle(color: Colors.white,fontSize: 12.sp,fontWeight: FontWeight.bold),),
          Obx(() => Text("${timer.actionTime.value}",style: TextStyle(color: Colors.white,fontSize: 8.sp),))
        ],
      )
    );
  }

  _itemBuilder(index){
    var item = _list[index];
    return Container(
        padding: EdgeInsets.only(top: 16.h,bottom: 36.h,left: 26.w,right: 16.w),
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/borrow_item_bg.png",
            ),
          ),
        ),
        // alignment: Alignment.center,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Image.asset("assets/images/item_icon.png",width: 10.w,fit: BoxFit.fitWidth,),
                SizedBox(width: 290.w,child: Text(' ${item.bookTitle}',style: TextStyle(color: Colors.blueAccent,fontSize: 10.sp)),),
                Text('归还成功',style: TextStyle(color: const Color.fromRGBO(19, 136, 8, 1),fontSize: 10.sp))
              ],
            ),
            SizedBox(height: 5.h,),
            const Divider(height: 1.0,color: Colors.grey,),
            SizedBox(height: 10.h,),
            Text('图书编号：${item.bookNo}',style: TextStyle(color: Colors.grey,fontSize: 8.sp)),
            Text('归还时间：${formatDate(DateTime.now(), [yy,'年',mm,'月',dd,'日 ',HH, ':', nn])}',style: TextStyle(color: Colors.grey,fontSize: 8.sp))
          ],
        )
    );
  }


  _gif(){
    return Container(
      alignment: Alignment.bottomRight,
      margin: EdgeInsets.only(top: 400.h),
      width: double.infinity,
      padding: EdgeInsets.only(left: 50.w),
      child: Image.asset( "assets/images/guide_gif.gif",),
    );
  }

  _books(){
    return  Obx(() => _list.isEmpty? _gif():
        Expanded(child: ListView.builder(
          itemBuilder: (context, index) {
            return _itemBuilder(index);
          },
          itemCount: _list.length,
        ))
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/bg.png",
            ),
          ),
        ),
        child: Column(
          children: [
            appBar(),
            _title(),
            _books(),

          ],
        ),
      ),
    );
  }
}

